package org.jeecg.glr.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.glr.entity.GlrRadio;
import org.jeecg.glr.entity.GlrVideo;
import org.jeecg.glr.entity.GlrVideoYs;
import org.jeecg.glr.mapper.GlrRadioMapper;
import org.jeecg.glr.mapper.GlrVideoMapper;
import org.jeecg.glr.mapper.GlrVideoYsMapper;
import org.jeecg.glr.service.IGlrRadioService;
import org.jeecg.glr.service.IGlrVideoYsService;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.glr.util.HttpRequestUtil;
import org.jeecg.glr.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Description: 视频萤石
 * @Author: jeecg-boot
 * @Date:   2020-02-11
 * @Version: V1.0
 */
@Service
public class GlrVideoYsServiceImpl extends ServiceImpl<GlrVideoYsMapper, GlrVideoYs> implements IGlrVideoYsService {

    @Resource
    private GlrVideoYsMapper glrVideoYsMapper;
    @Autowired
    private GlrVideoMapper glrVideoMapper;

    public String getToken(String videoYsId){
        GlrVideoYs entity = super.getById(videoYsId);
        return getToken(entity);
    }

    @Override
    public GlrVideoYs getGlrVideoYsByCode(String code) {
        return glrVideoYsMapper.getTokenByVideoYsCode(code);
    }

    public String getToken(GlrVideoYs entity){
        String stToken = "";
        if(entity.getExpirationDate() == null
                || entity.getExpirationDate().getTime() < DateUtils.getDateAddMinuteTime(10).getTime()){
            try
            {
                String stAPPKEY = entity.getAppKey();
                String stAPPSECRET = entity.getSecret();
                String url = HttpRequestUtil.YS_TOKEN_URL.replaceAll("APPKEY", stAPPKEY).replaceAll("APPSECRET",
                        stAPPSECRET);
                JSONObject json = HttpRequestUtil.httpRequest(url, "POST", null);
                //JSONObject json = JSONObject.fromObject("{\"msg\":\"操作成功!\",\"code\":\"200\",\"data\":{\"expireTime\":1558935170465,\"accessToken\":\"at.al61q67n10193ssf1u7w3xff15jb3bha-5mlmjssash-0zvvncb-j98ftbzjp\"}}");
                if(json.get("code").toString().equals("200")){
                    LinkedHashMap  jsonObject1=(LinkedHashMap)json.get("data");

                    String st1 = jsonObject1.get("expireTime").toString();
                    String accessToken = jsonObject1.get("accessToken").toString();

                    Date expirationDate = DateUtils.getDate(Long.parseLong(st1));

                    GlrVideoYs videoYS = super.getById(entity.getId());
                    videoYS.setAccessToken(accessToken);
                    videoYS.setExpirationDate(expirationDate);
                    super.updateById(videoYS);
                }
                else
                {
                    throw new Exception("error");
                }
            }
            catch (Exception ex){
                GlrVideoYs videoYS = super.getById(entity.getId());
                videoYS.setAccessToken("");
                videoYS.setExpirationDate(null);
                super.updateById(videoYS);
            }
            entity = super.getById(entity.getId());
        }
        stToken = entity.getAccessToken();
        return stToken;
    }



    public void updateGlrVideoStatus(GlrVideo domain){
        //GlrVideoYs glrVideoYs=getById(GLRConstant.GLR_VIDEO_YS_GAOTAI_ID);

        GlrVideoYs glrVideoYs=null;
        if(StringUtil.isNotEmpty(domain.getVideoYsCode())){
            QueryWrapper queryWrapperFind = QueryGenerator.initQueryWrapperCode();
            queryWrapperFind.eq("code",domain.getVideoYsCode());
            List<GlrVideoYs> listFind = list(queryWrapperFind);
            if (listFind.size()>0){
                glrVideoYs=listFind.get(0);
            }
        }
        String stToken = getToken(glrVideoYs);
        glrVideoYs.setAccessToken(stToken);
        updateGlrVideoStatus(domain,glrVideoYs);
    }

    public void updateGlrVideoStatus(GlrVideo domain,GlrVideoYs glrVideoYs){
        if (domain==null){
            return;
        }
        domain.setEquipmentStatus(GLRConstant.YN_N);
        //if (StringUtil.isNotEmpty(domain.getVideoYsId())&&glrVideoYs!=null&&domain.getVideoYsId().equals(glrVideoYs.getId())){
        if (StringUtil.isNotEmpty(domain.getVideoYsCode())&&glrVideoYs!=null){
            //GlrVideoYs glrVideoYs=getById(domain.getVideoYsId());
            domain.setGlrVideoYs(glrVideoYs);
            //String stToken = getToken(glrVideoYs);
            String stEquipmentStatus = getStatus(domain, glrVideoYs.getAccessToken());
            domain.setEquipmentStatus(stEquipmentStatus);
        }
    }

    public String getStatus(GlrVideo entity, String stACCESSTOKEN){
        //离线GLRConstant.IS_N/在线GLRConstant.IS_N
        String stReturn = GLRConstant.YN_N;
        if(StringUtil.isNotEmpty(stACCESSTOKEN)){
            String stDEVICESERIAL = entity.getEquipmentSerial();
            if (StringUtil.isEmpty(stDEVICESERIAL)) stDEVICESERIAL="";
            if (stDEVICESERIAL.length()==0||stDEVICESERIAL.length()!=9){
                return stReturn;
            }
            String url = HttpRequestUtil.YS_DEVICE_INFO_URL.replaceAll("ACCESSTOKEN", stACCESSTOKEN)
                    .replaceAll("DEVICESERIAL", stDEVICESERIAL);
            JSONObject json = HttpRequestUtil.httpRequest(url, "POST", null);
            //JSONObject json = JSONObject.fromObject("{\"msg\":\"操作成功!\",\"code\":\"200\",\"data\":{\"deviceSerial\":\"D12287823\",\"alarmSoundMode\":0,\"defence\":0,\"model\":\"DS-2DC7423IW-A\",\"offlineNotify\":0,\"category\":\"UNKNOWN\",\"deviceName\":\"我的测试\",\"status\":0,\"isEncrypt\":0}}");
            //System.out.println(json.toString());
            if(json.get("code").toString().equals("200")){
                LinkedHashMap  jsonObject1=(LinkedHashMap)json.get("data");
                String ststatus = jsonObject1.get("status").toString();
                //在线状态：0-不在线，1-在线
                if("0".equals(ststatus)) stReturn = GLRConstant.YN_N;
                if("1".equals(ststatus)) stReturn = GLRConstant.YN_Y;
            }
        }
        return stReturn;
    }

    public List<Map<String, Object>> doGetListForJdbc(String sqlStr){
        return glrVideoYsMapper.doGetListForJdbc(sqlStr);
    }

    public JSONObject getAddress(String videoId, String stACCESSTOKEN){
        //离线11/在线10
        JSONObject stReturn = new JSONObject();
        if(StringUtil.isNotEmpty(stACCESSTOKEN))
        {
            GlrVideo entity = glrVideoMapper.selectById(videoId);
            if(entity.getEquipmentSerial().length()==9&&(StringUtil.isEmpty(entity.getEquipmentUrl())||entity.getEquipmentUrl().indexOf("null")>0||entity.getEquipmentUrl().indexOf("\"\"")>0))
            {

                String stSOURCE = entity.getEquipmentSerial() + ":" + entity.getEquipmentChannel();
                try
                {
                    stSOURCE = URLEncoder.encode(stSOURCE, "GBK");
                }
                catch (UnsupportedEncodingException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String url ="";
                com.alibaba.fastjson.JSONObject json =null;
                if (entity.getEquipmentVerification()!=null&&entity.getEquipmentVerification().length()>0&&entity.getEquipmentSerial().length()>0){
                    url = HttpRequestUtil.YS_DEVICE_ENRYPT_URL.replaceAll("ACCESSTOKEN", stACCESSTOKEN)
                            .replaceAll("DEVICESERIAL", entity.getEquipmentSerial()).replaceAll("VALIDATECODE", entity.getEquipmentVerification());
                    json = HttpRequestUtil.httpRequest(url, "POST", null);
                    if(json.get("code").toString().equals("200")){

                    }else{
                        //System.out.println(json.get("code").toString()+json.get("msg").toString());
                    }
                }



                url = HttpRequestUtil.YS_DEVICE_LIVE_ADDRESS_URL.replaceAll("ACCESSTOKEN", stACCESSTOKEN)
                        .replaceAll("SOURCE", stSOURCE);
                json = HttpRequestUtil.httpRequest(url, "POST", null);
                //JSONObject json = JSONObject.fromObject("{\"msg\":\"操作成功!\",\"code\":\"200\",\"data\":{\"deviceSerial\":\"D12287823\",\"alarmSoundMode\":0,\"defence\":0,\"model\":\"DS-2DC7423IW-A\",\"offlineNotify\":0,\"category\":\"UNKNOWN\",\"deviceName\":\"我的测试\",\"status\":0,\"isEncrypt\":0}}");
                //System.out.println(json.toString());
                if(json.get("code").toString().equals("200"))
                {
                    List jsonArray= (List)json.get("data");
                    //JSONArray jsonArray = JSONArray.fromObject(json.get("data").toString());
                    if(jsonArray.size() > 0)
                    {
                        LinkedHashMap json1=(LinkedHashMap)jsonArray.get(0);
                        //net.sf.json.JSONObject json1 = jsonArray.getJSONObject(0);//把每一个对象转成json对象
                        //{"exception":1,"ret":"200","channelNo":1,"hlsHd":"http://hls01open.ys7.com/openlive/6d54ad70e0a540548b42b74c7763b2fa.hd.m3u8","deviceName":"我的测试","hls":"http://hls01open.ys7.com/openlive/6d54ad70e0a540548b42b74c7763b2fa.m3u8","hdFlvAddress":"https://flvopen.ys7.com:9188/openlive/6d54ad70e0a540548b42b74c7763b2fa.hd.flv","rtmp":"rtmp://rtmp01open.ys7.com/openlive/6d54ad70e0a540548b42b74c7763b2fa","deviceSerial":"D12287823","flvAddress":"https://flvopen.ys7.com:9188/openlive/6d54ad70e0a540548b42b74c7763b2fa.flv","rtmpHd":"rtmp://rtmp01open.ys7.com/openlive/6d54ad70e0a540548b42b74c7763b2fa.hd","status":1,"desc":"获取成功!"}
                        String hlsHd = "";
                        if (StringUtil.isNotEmpty(json1.get("hlsHd"))&&!("null".equals(json1.get("hlsHd").toString()))){
                            hlsHd = json1.get("hlsHd").toString();
                        }
                        String hls = "";
                        if (StringUtil.isNotEmpty(json1.get("hls"))&&!("null".equals(json1.get("hls").toString()))){
                            hls = json1.get("hls").toString();
                        }
                        String rtmp = "";
                        if (StringUtil.isNotEmpty(json1.get("rtmp"))&&!("null".equals(json1.get("rtmp").toString()))){
                            rtmp = json1.get("rtmp").toString();
                        }
                        String rtmpHd = "";
                        if (StringUtil.isNotEmpty(json1.get("rtmpHd"))&&!("null".equals(json1.get("rtmpHd").toString()))){
                            rtmpHd = json1.get("rtmpHd").toString();
                        }
                        //stReturn=sthlsHd;
                        if (StringUtil.isNotEmpty(hlsHd)&&StringUtil.isNotEmpty(hls)&&StringUtil.isNotEmpty(rtmpHd)&&StringUtil.isNotEmpty(rtmp)){
                            stReturn.put("hlsHd", hlsHd);
                            stReturn.put("hls", hls);
                            stReturn.put("rtmpHd", rtmpHd);
                            stReturn.put("rtmp", rtmp);

                            entity.setEquipmentUrl(stReturn.toString());
                            glrVideoMapper.updateById(entity);
                        }

                    }
                    //JSONObject json1 = JSONObject.fromObject(json.get("data").toString());
                    //String ststatus=json1.get("status").toString();
                    //在线状态：0-不在线，1-在线
                    //if ("0".equals(ststatus))stReturn="11";
                    //if ("1".equals(ststatus))stReturn="10";
                }
            }
            else
            {
                try{
                    String stEquipmentUrl=entity.getEquipmentUrl();
                    if (StringUtil.isNotEmpty(stEquipmentUrl)){
                        stReturn = JSONObject.parseObject(stEquipmentUrl);
                    }else{
                        throw new Exception("111");
                    }
                }catch (Exception ex){
                    stReturn.put("hlsHd","");
                    stReturn.put("hls","");
                    stReturn.put("rtmp","");
                    stReturn.put("rtmpHd","");
                }
            }
        }

        return stReturn;
    }

    public int insertSql(String sql){
        return  glrVideoYsMapper.insertSql(sql);
    }

    public int updateSql(String sql){
        return glrVideoYsMapper.updateSql(sql);
    }

    public int deleteSql(String sql){
        return glrVideoYsMapper.deleteSql(sql);
    }

    public void updateBatchSql(List<String> sqlList){
        glrVideoYsMapper.updateBatchSql(sqlList);
    }

    public GlrVideoYs getVideoByCode(String videoYsCode){
        GlrVideoYs glrVideoYs=null;
        if(StringUtil.isNotEmpty(videoYsCode)){
            QueryWrapper queryWrapper = QueryGenerator.initQueryWrapperCode();
            queryWrapper.eq("code",videoYsCode);
            List<GlrVideoYs> list = list(queryWrapper);
            if (list.size()>0){
                glrVideoYs=list.get(0);
            }
        }
        return glrVideoYs;
    }
}
